package com.example.sender;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.example.bean.FilePart;
import com.example.constant.ClientConstants;
import com.example.util.DataBuilder;
import com.example.util.Des;

public class TcpSender {
	
	private final static Logger log = LoggerFactory.getLogger(TcpSender.class);
	
	protected Socket socket;
	
	protected String ip;
	
	protected int port;
	
	public TcpSender(String ip, int port) throws Exception {
		this.ip = ip;
		this.port = port;
	}
	
	public void sendStream(File file) throws Exception {
		socket = new Socket(ip, port);
		
		byte[] buffer = new byte[512];
		
		log.info("sending file to server {}:{}", ip, port);
		InputStream input = new FileInputStream(file);
		BufferedOutputStream output = new BufferedOutputStream(socket.getOutputStream());
		
//		String md5 = DataBuilder.buidMD5Checksum(file);
//		System.out.println("send file md5 is + md5");
//		output.write(md5.getBytes(), 0, md5.getBytes().length);
//		output.flush();
		
/*		
		while((len = input.read(buffer)) != -1){
			FilePart part = new FilePart();
			if(len < buffer.length){
				// 读到文件尾
				byte[] data = new byte[len];
				System.arraycopy(buffer, 0, data, 0, len);
				part.data = data;
			}else{
				part.data = buffer;
			}
			
			String s = Des.encryptDES(DataBuilder.buildJson(part), ClientConstants.key, ClientConstants.key);
			log.info("send string -> {}", s);
			byte[] source = s.getBytes("UTF-8");
			output.write(source, 0, source.length);
			output.flush();
		}
*/
//		int count = 1;
		
		int len = -1;
		
		while((len = input.read(buffer)) != -1){
			byte[] data = buffer;
			
			if(len < buffer.length){
				// 读到文件尾
				data = new byte[len];
				System.arraycopy(buffer, 0, data, 0, len);
			}
			
			output.write(data, 0, data.length);
			output.flush();
		}
//		output.flush();
		output.close();
		input.close();
		socket.close();
		
		log.info("Send file done!!");
	}
}
